import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
} from '@nestjs/common';

// import type { Request, Response } from 'express';
import type { Response } from 'express';
import { IErrorIntercept, IErrorInterceptData0 } from '@/types/globalType';
@Catch(HttpException)
export class ErrorIntercept implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    // const request = ctx.getRequest<Request>();
    const response = ctx.getResponse<Response>();
    console.log(
      '触发全局异常拦截器',
      exception.getResponse(),
      exception.getStatus(),
    );

    const status = exception.getStatus();
    const content = exception.getResponse() as IErrorIntercept;
    // console.log('status', status, request., response);
    if (content.type == '0') {
      // 程序错误
      const data = content.data as IErrorInterceptData0;
      return response.status(status).json({
        // data: exception.getResponse(), // 这个才是错误信息
        // data: exception.message,
        // time: new Date().getTime(),
        // success: false,
        // path: request.url,
        // status,
        data: '', // 这里的data 就是控制器，return的东西
        state: '0',
        errMsg: data.errMsg || '',
        errCode: data.errCode,
        errStack: data.errStack || '',
      });
    } else if (content.type == '1') {
      console.log('全局异常拦截器:前端入参错误');

      // 前端入参错误
      return response.status(status).json({
        data: content.data,
        state: '1',
        errMsg: null,
        errCode: null,
        errStack: null,
      });
    }

    if (status == 404) {
      const res = content as any;
      return response.status(status).json({
        data: '',
        state: '0',
        errMsg: `${res.message}`,
        errCode: 'ErrCode-00005',
        errStack: null,
      });
    }
  }
}
